import type { PrintRequest, PrintResponse, PrintTemplate } from "@/pages/tool/printTemplate/entity";
import apiClient from "../../apiClient";

export interface PageListReq {
	//名称
	name?: string;
	//当前页码
	page: number;
	//每页数量
	pageSize: number;
}

export interface PageListRes {
	//总记录数
	total: number;
	//数据列表
	records: PrintTemplate[];
}

const pageList = (data: PageListReq): Promise<PageListRes> =>
	apiClient.post({
		url: "/tool/print/template/pageList",
		data,
	});

const selectList = (): Promise<PrintTemplate[]> =>
	apiClient.get({
		url: "/tool/print/template/selectList",
	});

const getInfo = (id: React.Key): Promise<PrintTemplate> =>
	apiClient.get({
		url: `/tool/print/template/${id}`,
	});

const add = (data: PrintTemplate): Promise<PrintTemplate> =>
	apiClient.post({
		url: "/tool/print/template",
		data,
	});

const update = (data: PrintTemplate): Promise<PrintTemplate> =>
	apiClient.put({
		url: "/tool/print/template",
		data,
	});

const remove = (ids: React.Key[]): Promise<void> =>
	apiClient.delete({
		url: "/tool/print/template",
		params: {
			ids: ids.join(","),
		},
	});

// 获取数据源
const getDatasource = (): Promise<any[]> =>
	apiClient.get({
		url: "/tool/print/template/dataSource",
	});

const download = (id: React.Key): Promise<void> =>
	apiClient.get({
		url: `/tool/print/template/download/${id}`,
	});

const design = (id: React.Key): Promise<PrintResponse> =>
	apiClient.get({
		url: `/tool/print/template/design/${id}`,
	});

// 打印
const print = (printRequest: PrintRequest): Promise<PrintResponse> =>
	apiClient.post({
		url: "/tool/print/template/print",
		data: printRequest,
	});

// 获取模板字段
const getTemplateFields = (id: React.Key): Promise<any[]> =>
	apiClient.get({
		url: `/tool/print/template/field/${id}`,
	});

// 获取模板JSON
const getTemplateJson = (id: React.Key): Promise<string> =>
	apiClient.get({
		url: `/tool/print/template/designer/json/${id}`,
		responseType: "text",
	});

// 保存设计器JSON
const saveDesignerJson = (data: PrintTemplate): Promise<void> =>
	apiClient.post({
		url: "/tool/print/template/hiprint",
		data,
	});

export const printTemplateService = {
	pageList,
	selectList,
	getInfo,
	add,
	update,
	remove,
	getDatasource,
	download,
	design,
	print,
	getTemplateFields,
	getTemplateJson,
	saveDesignerJson,
};

export default printTemplateService;
